package com.study.base.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @description: NIOClient
 * @date: 2021/1/21 19:26
 * @author: hcm
 * @version: 1.0
 */
public class NIOClient {
    public static void main(String[] args) throws IOException {
        //得到一个网络通道
        SocketChannel socketChannel = SocketChannel.open();
        //设置非阻塞模式
        socketChannel.configureBlocking(false);
        //提供服务器端的ip和端口
        InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1",666);

        //连接服务器
        if(!socketChannel.connect(socketAddress)){
            while (!socketChannel.finishConnect()){
                System.out.println("因为连接需要时间，客户端不要阻塞，可以做其他工作");
            }
        }
        //连接成功，发送数据
        String str = "hello , 特朗普";
        ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
        //发送数据，写入channel
        socketChannel.write(buffer);
        System.in.read();
    }
}
